require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var AttrSchema = Schema({
  _id: false,
  key: String,
  value: String
});


/**
  关联关系实例属性根据Relation定义的属性动态变化，strict: false
  src和dest引用的是模型实例
 */
var bizrelainstSchema = Schema({
  desc: { type: String },
  src: { type: Schema.Types.ObjectId, ref: 'Bizinst' },
  dest: { type: Schema.Types.ObjectId, ref: 'Bizinst' },
  rela: { type: Schema.Types.ObjectId, ref: 'Bizrela' },
  attrs: [AttrSchema]
}, { strict: false })

bizrelainstSchema.statics = {
  page: function (query, page, limit, callback) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20
    Bizrelainst.count(query).then(total => {
      Bizrelainst
        .find(query)
        .skip((page) * limit)
        .limit(limit * 1)
        .populate('src')
        .populate('dest')
        .populate('rela')
        .exec((err, docs) => {
          callback({
            pageable: {
              totalElements: total,
              numberOfElements: docs.length,
              totalPages: Math.ceil(total / limit),
              number: page,
              first: page == 0,
              last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
              size: limit,
              fromNumber: page * limit,
              toNumber: page * limit + docs.length
            },
            docs
          })
        })
    })
  }
}

var Bizrelainst = mongoose.model('Bizrelainst', bizrelainstSchema);

module.exports = Bizrelainst
